import axios from "axios";
import { MessagePlugin } from "tdesign-vue-next";
import errorCode from "@/utils/error-code";
import { BASE_URL } from "./config";

// 创建axios实例
const request = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
});

// 错误信息处理
const handleError = (message) => {
  if (message === "Network Error") {
    return "后端接口连接异常";
  } else if (message.includes("timeout")) {
    return "系统接口请求超时";
  } else if (message.includes("请求失败，状态码错误")) {
    return (
      "系统接口 " + message.substr(message.length - 3) + " 异常"
    );
  }
  return message;
};

// 错误处理函数
const errorHandler = (error) => {
  console.error("Request error:", error);
  const errorMessage = handleError(error.message);
  if (errorMessage) {
    MessagePlugin.error(errorMessage);
  }
  return Promise.reject(error);
};

// 请求拦截器
const requestInterceptor = (config) => {
  const authorization = sessionStorage.getItem("authorization");
  if (authorization) {
    config.headers.Authorization = `Basic ${authorization}`;
  }
  return config;
};

// 响应拦截器
const responseInterceptor = (response) => {
  const { code, errorCode: responseErrorCode, msg } = response.data;
  const errorMessage =
    errorCode[responseErrorCode] || msg || errorCode["default"];

  // 如果响应类型为blob或arraybuffer，直接返回数据
  if (
    response.request.responseType === "blob" ||
    response.request.responseType === "arraybuffer"
  ) {
    return response.data;
  }

  // 错误码处理
  if (code === 500 || code !== 0) {
    MessagePlugin.error(errorMessage);
    return Promise.reject(errorMessage);
  }

  return response.data;
};

// 注册请求和响应拦截器
request.interceptors.request.use(requestInterceptor, errorHandler);
request.interceptors.response.use(responseInterceptor, errorHandler);

export default request;
